import logging
import time

import pytest
from selenium import webdriver
from pages.page import LoginPage
import os
import sys
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
print(sys.path)

logger = logging.getLogger(__name__)


@pytest.fixture(scope='session')
def driver():
    driver = webdriver.Chrome()
    driver.maximize_window()
    yield driver
    driver.quit()


@pytest.fixture(scope="module")
def user_driver():
    driver = webdriver.Chrome()
    driver.maximize_window()
    LoginPage(driver).go_to_url("https://gj.kdzwy.com/index_new.html")
    LoginPage(driver).login_zhangwuyou()
    yield driver
    driver.quit()


def pytest_runtest_setup(item):
    logger.info(f"开始执行:{item.nodeid}".center(60, "_"))


def pytest_runtest_teardown(item):
    logger.info(f"执行结束:{item.nodeid}".center(60, "_"))


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    path = f"images/{time.time()}.png"

    if report.when == "call":
        o = report.outcome
        s = f"用例执行结果：【{report.outcome}】"
        if o == "failed":
            logger.error(s)
        elif o == "skip":
            logger.warning(s)
        else:
            logger.info(s)

        if "user_driver" in item.fixturenames:
            driver = item.funcargs["user_driver"]
            logger.info(f"页面截图：{path}")
            driver.get_screenshot_as_file(path)
